﻿/**************************************************************
 *
 * 唯一标识：63964459-07af-4c3a-a43b-2bd80ebec916
 * 命名空间：Sgr.UPMS.Application.Commands.Departments
 * 创建时间：2023/8/27 20:00:00
 * 机器名称：DESKTOP-S0D075D
 * 创建者：antho
 * 电子邮箱：fengqinhua2016@163.com
 * 描述：更新部门命令处理器
 *
 **************************************************************/

using MediatR;
using Sgr.Application.Commands;
using Sgr.Domain.Entities;
using Sgr.UPMS.Domain.Departments;

namespace Sgr.UPMS.Application.Commands.Departments
{
    /// <summary>
    /// 更新部门命令处理器
    /// </summary>
    public class UpdateDepartmentCommandHandle : IRequestHandler<UpdateDepartmentCommand, CommandResult<bool>>
    {
        private readonly IDepartmentRepository _departmentRepository;
        private readonly IDepartmentManage _departmentManage;

        public UpdateDepartmentCommandHandle(
            IDepartmentRepository departmentRepository,
            IDepartmentManage departmentManage)
        {
            _departmentRepository = departmentRepository;
            _departmentManage = departmentManage;
        }

        public async Task<CommandResult<bool>> Handle(UpdateDepartmentCommand request, CancellationToken cancellationToken)
        {
            // 查找部门实体
            var department = await _departmentRepository.GetAsync(request.DepartmentId, cancellationToken);

            // 如果找不到部门，返回NotFound结果
            if (department == null)
                return CommandResult.NotFound<bool>("未找到指定的部门");

            // 更新部门信息
            department.ChangeName(request.Name);

            // 使用IDepartmentManage处理状态变更
            if (request.State == EntityStates.Normal)
                await _departmentManage.ActivateAsync(department, cancellationToken);
            else if (request.State == EntityStates.Deactivate)
                await _departmentManage.DeactivateAsync(department, cancellationToken);

            // 更新其他信息
            department.Remarks = request.Remarks;
            department.OrderNumber = request.OrderNumber;
            department.ChangeManagerUser(request.ManagerUserId, request.Leader, request.Phone, request.Email);
            department.MarkAsChanged();

            // 更新到仓储
            await _departmentRepository.UpdateAsync(department, cancellationToken);

            // 返回成功结果
            return CommandResult.Success(true, "部门信息更新成功");
        }
    }
}